#!/bin/bash

UNAME=`uname`

if [ "${UNAME}" = "Darwin" ]; then
    echo "Should run in Vagrant Linux. not Mac"
    exit 1
fi

set -x

#$1= {local,remote}
#$2= {user}

# eg.
# ./linux-pack.sh local thyang
# ./linux-pack.sh local 2751222
LOCAL=$1
USER=$2

# goto hookfish directory
OLD_DIR=`pwd`
HOOKFISH_HOME="$GOPATH/src/hookfish"
cd $HOOKFISH_HOME

#clean up
echo "clean..."
rm -Rf ./run

#move static
echo "Prepare static file..."
mkdir ./run
mkdir ./run/hookfish$USER
mkdir ./run/hookfish$USER/log

cp -fr hookfish.conf ./run/hookfish$USER
cp -fr hookfish.sh ./run/hookfish$USER
cp -fr install-to-supervisor.sh ./run/hookfish$USER

#go build
echo "Building hookfish..."
go build

#move program
cp -rf ./hookfish ./run/hookfish$USER/
chmod +x ./run/hookfish$USER/hookfish

#override settings
echo "Override user settings"
sed -i "s/username/$2/g" ./run/hookfish$USER/*.conf
sed -i "s/username/$2/g" ./run/hookfish$USER/*.sh

sed -i "s/thyang/$2/g" ./run/hookfish$USER/*.conf
sed -i "s/thyang/$2/g" ./run/hookfish$USER/*.sh

#compress
cd run && tar -czf hookfish$USER.tar hookfish$USER
echo "Linux Pack Done: ./run/hookfish$USER.tar"

#upload to server.
echo "Prepare to Upload.(Special Machine)"
UPLOAD_HOME="/home/ftp-user"

# Copy to Local or Remote Server
# $./linux-pack.sh local
# $./linux-pack.sh
if [ "$1" = "local"  ]; then
	echo "Copy to Local"
	sudo mv hookfish$USER.tar $UPLOAD_HOME
else
	echo "Copy to Server"
	scp hookfish$USER.tar ftp-user@218.244.150.208:$UPLOAD_HOME
fi

# clean reload
echo "Upload Done"

echo "Warning:"
echo "Update your email&password in hookfish$USER/hookfish.sh"
echo ""

cd $OLD_DIR
